<template>
	<view class="pa">
		<!-- 正常商品 -->
		<product-detail-normal v-if="type == 1 && getCode" :detailSku="detailSku" :productDetail="productDetail" :detailkutype="detailkutype" :banner_num="banner_num"
		 :detail_pic="detail_pic" :showSize="showSize" @specificationBtn="specificationBtn" :choose_size="choose_size" @login="login"></product-detail-normal>
		<!-- 限时秒杀 -->
		<product-detail-seckill v-else-if="type == 0 && getCode" :detailSku="detailSku"  :productDetail="productDetail" :banner_num="banner_num"
		 :detailkutype="detailkutype" :detail_pic="detail_pic" :showSize="showSize" @specificationBtn="specificationBtn" :choose_size="choose_size" @login="login"></product-detail-seckill>
		<!-- 超级拼团 -->
		<product-detail-group v-else-if="type == 3 && getCode" :detailSku="detailSku" :productDetail="productDetail" :banner_num="banner_num" :choose_size="choose_size"
		 :detailkutype="detailkutype" :detail_pic="detail_pic" :showSize="showSize" @specificationBtn="specificationBtn" :user_assemble_id="user_assemble_id" @login="login"></product-detail-group>
		<!-- 积分 -->
		<product-detail-integral v-else-if="type == 2 && getCode && showDetailFlag" :detailSku="detailSku" :productDetail="productDetail" :banner_num="banner_num"
		 :detail_pic="detail_pic" @login="login"></product-detail-integral>
		<shop-loading v-if="shopLoad"></shop-loading>
		<sc-no v-if="!getCode" :noStatus="false" @navtive="navtive" url="add_images/expired_goods.png" nofont="商品过期不存在"></sc-no>
		<uni-login ref='login' @success="loginSuccess" @error="loginError"></uni-login>
		<sc-home></sc-home>
	</view>
</template>

<script>
	import uniPopup from '@/components/uni-popup/uni-popup.vue';
	import uniCountdown from '@/components/uni-countdown/uni-countdown.vue';
	import nowGroup from '@/components/nowgroup/nowgroup.vue'
	import uniCountdowno from '@/components/uni-countdown/uni-countdown1.vue';
	import goodsComment from '@/components/goodsComment/goodsCommentList.vue'
	import recommendGoods from '@/components/indexRecommend/recommendList.vue'
	import scNo from '@/components/sc-no/sc-no.vue';
	//正常商品 商品详情
	import productDetailNormal from '@/pageB/classify/productdetail_normal.vue'
	//限时秒杀 商品详情
	import productDetailSeckill from '@/pageB/classify/productdetail_seckill.vue'
	//超级拼团 商品详情
	import productDetailGroup from '@/pageB/classify/productdetail_group.vue'
	//积分商城 商品详情
	import productDetailIntegral from '@/pageB/classify/productdetail_integral.vue'
	import {
		detail,
		seckillDetail,
		integralDetail,
		collageDetail
	} from '@/common/productdetail.js';
	export default {
		components: {
			uniPopup,
			uniCountdown,
			nowGroup,
			uniCountdowno,
			goodsComment,
			recommendGoods,
			productDetailNormal,
			productDetailSeckill,
			productDetailGroup,
			productDetailIntegral,
			scNo
		},
		data() {
			return {
				getCode:0,
				shopLoad: true,
				id: 1,
				productDetail: {},
				type: '', //判断进来的路径  是积分还是秒杀  或者普通商品 1(正常商品)，0(秒杀商品),2(积分商品),3(拼团商品)
				// state_type: '', //限时秒杀的状态：0(正在秒杀),1(等待下一场秒杀),2(秒杀活动结束)
				detail_pic: '',
				detailSku: {},
				detailkutype: {
					selectArr: [], //选中
					subIndex: [], //判断是否选中
					shopItemInfo: {}, //存放选中的值和匹配的数据
					SizeData: [], //排列好的数据集合
					totalSize: [], //初始的数据集合
					proSku: {},
					price: '',
					Stock: '',
					Stockpic: ''
				},
				showSize: true,
				banner_num: '0',
				choose_size:'请选择规格',
				user_assemble_id:0,
				showDetailFlag:false,
				shopId:0
			};
		},
		onLoad(options) {
			this.type = options.type
			this.id = options.id
			this.user_assemble_id = +options.user_assemble_id
			// console.log(options)
			// console.log(this.type);
			// console.log("传过来的id值为" + this.id)
			this.getProductDetail()
			uni.removeStorageSync('mineRefresh');
		},
		onShareAppMessage(res) {
			const {productDetail,type,shopId,state_type} = this;
		    if (res.from === 'button') {// 来自页面内分享按钮
		      console.log(res.target)
		    }
		    return {
		      title:productDetail.name,
		      path: '/pageB/classify/productdetail?id='+shopId+'&type='+type,
			  imageUrl:productDetail.cover
		    }
		},
		methods: {
			login() {
				if(uni.getSystemInfoSync().version){
				   this.$refs.login.show = true;	
				}
			},
			loginSuccess(){
				uni.setStorageSync('mineRefresh',1)
				this.getProductDetail()
			},
			loginError(){
				// console.log("失败")
				uni.removeStorageSync('mineRefresh');
				uni.navigateBack({
				    delta: 1
				});
			},
			jiekou(item) {
				// console.log('jiekou', item)
				const data = JSON.parse(JSON.stringify(item))
				// console.log('jiekou1', data)
				if (data.sizeData.length > 0) {
					this.showSize = true
					var defaultData = '';
					for(let i of data.sizeData){
						if(i.stock != 0){
							defaultData = i.specs;
							break;
						}
					}
					let list = defaultData.split(',');
					let caseData = data.totalSize;
					var indexiL = [];
					this.detailkutype.selectArr = list; 
					// this.choose_size = list.toString();
					this.choose_size = list.toString() ? list.toString():'请选择规格';
					for (var i in data.sizeData[0]) {
						caseData.forEach((item, index) => {
							if (i === item.name) {
								console.log(i,item.name)
								indexiL.push(caseData[index].attr.findIndex(obj => obj.val === list[index]))
							}
						})
					}
					console.log(indexiL);
					this.detailkutype.subIndex = indexiL;
					for (var i in data.sizeData) {
						this.detailkutype.shopItemInfo[data.sizeData[i].specs] = data.sizeData[i]; //修改数据结构格式，改成键值对的方式，以方便和选中之后的值进行匹配
					}
				} else {
					this.showSize = false
				}
				// console.log('jiekou2',this.subIndex,this.shopItemInfo)
				this.checkItem();
			},
			checkItem() {
				let detail = this.productDetail;
				var sizeData = JSON.parse(JSON.stringify(detail.total_size));
				var option = sizeData;
				var result = []; //定义数组储存被选中的值
				for (var i in option) {
					result[i] = this.detailkutype.selectArr[i] ? this.detailkutype.selectArr[i] : '';
				}
				for (var i in option) {
					var last = result[i]; //把选中的值存放到字符串last去
					for (var k in option[i].attr) {
						result[i] = option[i].attr[k].val; //赋值，存在直接覆盖，不存在往里面添加name值
						option[i].attr[k].isShow = this.isMay(result); //在数据里面添加字段isShow来判断是否可以选择
					}
					result[i] = last; //还原，目的是记录点下去那个值，避免下一次执行循环时被覆盖
				}

				if (this.detailkutype.shopItemInfo[result]) {
					this.detailkutype.price = this.detailkutype.shopItemInfo[result].price;
					this.detailkutype.Stock = this.detailkutype.shopItemInfo[result].stock;
					this.detailkutype.Stockpic = this.detailkutype.shopItemInfo[result].pic;
				}else{
					this.detailkutype.price = this.productDetail.price;
				}
				// console.log(option)
				this.detailSku['totalSize'] = option
				this.$forceUpdate(); //重绘
			},
			isMay(result) {
				for (var i in result) {
					if (result[i] == '') {
						return true; //如果数组里有为空的值，那直接返回true
					}
				}
				// console.log('56456465456456456',this.detailkutype.shopItemInfo);
				// console.log('result',result)
				return this.detailkutype.shopItemInfo[result].stock == 0 ? false : true; //匹配选中的数据的库存，若不为空返回true反之返回false
			},
			specificationBtn(item, n, event, index, it) {
				// console.log(item, n, event, index)
				if (!it) {
					return false;
				}
				if (this.detailkutype.selectArr[n] != item) {
					this.detailkutype.selectArr[n] = item;
					this.detailkutype.subIndex[n] = index;
				} else {
					// this.detailkutype.selectArr[n] = "";
					this.detailkutype.selectArr.splice(n,1);
					this.detailkutype.subIndex.splice(n,1);
					// this.detailkutype.subIndex[n] = -1; //去掉选中的颜色
				}
				this.detailkutype.selectArr = JSON.parse(JSON.stringify(this.detailkutype.selectArr));
				this.detailkutype.subIndex = JSON.parse(JSON.stringify(this.detailkutype.subIndex));
				// console.log(this.detailkutype.selectArr, this.detailkutype.subIndex)
				this.choose_size = this.detailkutype.selectArr.toString() && this.detailkutype.selectArr.toString() != ',' ? this.detailkutype.selectArr.toString() :'请选择规格'
				this.checkItem();
			},
			cartesianProductOf() {
				return Array.prototype.reduce.call(arguments, function(a, b) {
					var ret = [];
					a.forEach(function(a) {
						b.forEach(function(b) {
							ret.push(a.concat([b]));
						});
					});
					return ret;
				}, [
					[]
				]);
			},
			getProductDetail() {
				this.getCode = 0
				this.shopLoad = true;
				let params = {
					id: this.id
				}
				if (this.type == 0) { //限时秒杀
					this.getSkillProductDetail(params)
				} else if (this.type == 1) { //普通商品
					this.getNormProductDetail(params)
				} else if (this.type == 2) { //积分商品
					this.getIntegralProductDetail(params)
				} else if (this.type == 3) { //拼团商品
					this.getGroupProductDetail(params)
				}


			},
			getSkillProductDetail(params) {
				seckillDetail(params).then(res => {
					// console.log(res)
					this.getCode = res.code
					if (res.code == 1) {
						// console.log("限时秒杀商品")
						// console.log(res.msg)
						this.productDetail = res.msg;
						this.shopId = res.msg.skill_id;
						this.detailSku = {
							totalSize: res.msg.total_size,
							sizeData: res.msg.size_data
						}
						let content = res.msg.detail
						const regex = new RegExp('<img', 'gi');
						content = content.replace(regex, '<img style="max-width: 100%;"');
						this.detail_pic = content;
						this.banner_num = this.productDetail.carousel.length
						this.jiekou(this.detailSku)
						this.shopLoad = false;
					} else {
						this.shopLoad = false;
					}

				}).catch()
			},
			getNormProductDetail(params) {
				detail(params).then(res => {
					this.getCode = res.code
					// console.log(res)
					if (res.code == 1) {
						this.productDetail = res.msg;
						this.shopId = res.msg.id;
						res.msg.size_data.forEach(item=>{
							item.stock = +item.stock;
						})
						this.detailSku = {
							totalSize: res.msg.total_size,
							sizeData: res.msg.size_data
						}
						let content = res.msg.detail
						const regex = new RegExp('<img', 'gi');
						content = content.replace(regex, '<img style="max-width: 100%;"');
						this.detail_pic = content;
						this.banner_num = this.productDetail.carousel.length
						this.jiekou(this.detailSku)
						this.shopLoad = false;
					} else {
						this.shopLoad = false;
					}
				}).catch()
			},
			getIntegralProductDetail(params) {
				integralDetail(params).then(res => {
					this.getCode = res.code
					// console.log(res)
					if (res.code == 1) {
						// console.log("积分商品")
						// console.log(res.msg)
						this.productDetail = res.msg;
						this.detailSku = {
							totalSize: res.msg.total_size,
							sizeData: res.msg.size_data
						}
						let content = res.msg.detail
						const regex = new RegExp('<img', 'gi');
						content = content.replace(regex, '<img style="max-width: 100%;"');
						this.detail_pic = content;
						this.shopLoad = false;
						this.showDetailFlag= true
					}else if (res.code == 4){
						this.showDetailFlag= false
						this.login()
					} else {
						this.showDetailFlag= false
						this.toast(res.msg)
						this.shopLoad = false;
					}
				}).catch()
			},
			getGroupProductDetail(params) {
				collageDetail(params).then(res => {
					this.getCode = res.code
					// console.log(res)
					if (res.code == 1) {
						// console.log("拼团商品")
						// console.log(res.msg)
						this.productDetail = res.msg;
						this.shopId = res.msg.assemble_id;
						this.detailSku = {
							totalSize: res.msg.total_size,
							sizeData: res.msg.size_data
						}
						let content = res.msg.detail
						const regex = new RegExp('<img', 'gi');
						content = content.replace(regex, '<img style="max-width: 100%;"');
						this.detail_pic = content;
						this.banner_num = this.productDetail.carousel.length
						this.jiekou(this.detailSku)
						this.shopLoad = false;
					} else {
						this.shopLoad = false;
					}
				}).catch()
			},

		}
	};
</script>

<style lang="less" scoped>
	@import url('../../static/scss/pageB/productdetail.less');
</style>
